from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
import re
from typing import Optional
from ..core.database import get_db
from sqlalchemy.orm import Session
from ..models.user import User
import secrets
import time

router = APIRouter(prefix="/auth", tags=["认证"])

class PhoneLoginRequest(BaseModel):
    phone: str
    code: str

class SendCodeRequest(BaseModel):
    phone: str

class PhoneLoginResponse(BaseModel):
    success: bool
    message: str
    access_token: Optional[str] = None
    user_info: Optional[dict] = None

class SendCodeResponse(BaseModel):
    success: bool
    message: str

# 存储验证码的简单缓存（生产环境应该使用Redis）
verification_codes = {}

# 手机号验证正则表达式
PHONE_PATTERN = re.compile(r'^1[3-9]\d{9}$')

def validate_phone(phone: str) -> bool:
    """验证手机号格式"""
    return bool(PHONE_PATTERN.match(phone))

@router.post("/send-code", response_model=SendCodeResponse)
async def send_verification_code(request: SendCodeRequest):
    """
    发送手机验证码
    """
    try:
        phone = request.phone
        
        # 验证手机号格式
        if not phone or not validate_phone(phone):
            raise HTTPException(status_code=400, detail="手机号格式不正确")
        
        # 生成验证码（默认111111）
        code = "111111"
        
        # 存储验证码（5分钟有效期）
        verification_codes[phone] = {
            "code": code,
            "expires_at": time.time() + 300  # 5分钟
        }
        
        # TODO: 这里应该调用短信服务发送验证码
        # 目前直接返回成功，验证码固定为111111
        
        return SendCodeResponse(
            success=True,
            message="验证码发送成功"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"发送验证码失败: {str(e)}")

@router.post("/phone-login", response_model=PhoneLoginResponse)
async def phone_login(request: PhoneLoginRequest, db: Session = Depends(get_db)):
    """
    手机号验证码登录
    """
    try:
        phone = request.phone
        code = request.code
        
        # 验证手机号格式
        if not phone or not validate_phone(phone):
            raise HTTPException(status_code=400, detail="手机号格式不正确")
        
        # 验证验证码
        if phone not in verification_codes:
            raise HTTPException(status_code=400, detail="请先发送验证码")
        
        stored_code_data = verification_codes[phone]
        
        # 检查验证码是否过期
        if time.time() > stored_code_data["expires_at"]:
            del verification_codes[phone]
            raise HTTPException(status_code=400, detail="验证码已过期，请重新发送")
        
        # 验证验证码
        if code != stored_code_data["code"]:
            raise HTTPException(status_code=400, detail="验证码错误")
        
        # 验证成功后删除验证码
        del verification_codes[phone]
        
        # 查找或创建用户
        user = db.query(User).filter(User.phone == phone).first()
        
        if not user:
            # 创建新用户
            user = User(
                openid=None,  # 手机号登录用户没有openid，设为None
                nickname=f"用户{phone[-4:]}",  # 使用手机号后4位作为昵称
                avatar_url="",  # 默认头像
                phone=phone
            )
            db.add(user)
            db.commit()
            db.refresh(user)
        else:
            # 更新用户信息
            if not user.nickname or user.nickname.startswith("用户"):
                user.nickname = f"用户{phone[-4:]}"
            db.commit()
        
        # 生成访问令牌
        access_token = secrets.token_urlsafe(32)
        
        # 返回用户信息
        return PhoneLoginResponse(
            success=True,
            message="登录成功",
            access_token=access_token,
            user_info={
                "openid": user.openid,
                "nickname": user.nickname,
                "avatar_url": user.avatar_url,
                "phone": user.phone
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"登录失败: {str(e)}")

@router.get("/user-info")
async def get_user_info(db: Session = Depends(get_db)):
    """
    获取当前用户信息
    """
    # TODO: 这里应该从token中获取用户信息
    # 目前简化处理，返回空信息
    return {"message": "需要登录"} 